<?php // XenonPHP Autoload Class v0.1

// Set Autoload Cache File (JSON Object). Comment the line below to deactivate autoload cache.
define('X_AUTOLOAD_CACHE_FILE', realpath(dirname(__FILE__) . '/application/cache') . '/autoload.json');

class X_Autoload
{
    public static $cachedAutoloadClasses = array();

    public static function __autoload($className)
    {
        // If Cache file exists, use cache
        if (defined('X_AUTOLOAD_CACHE_FILE') && X_AUTOLOAD_CACHE_FILE) {
            if (empty(self::$cachedAutoloadClasses) && is_file(X_AUTOLOAD_CACHE_FILE)) {
                // If Autoload Cache array is empty and cache file exists, fill it from cache file
                self::$cachedAutoloadClasses = json_decode(file_get_contents(X_AUTOLOAD_CACHE_FILE), true);
            }
            if (!empty(self::$cachedAutoloadClasses) && array_key_exists($className, self::$cachedAutoloadClasses)) {
                require_once self::$cachedAutoloadClasses[$className];
                return;
            }
        }

        // If no cache or class not found in cache, search for the file by path priority
        $include_paths = array(
            realpath(dirname(__FILE__) . '/application/controller'),
            realpath(dirname(__FILE__) . '/application/model'),
            realpath(dirname(__FILE__) . '/application/lib'),
            realpath(dirname(__FILE__) . '/application/xlib'),
        );
        foreach ($include_paths as $path) {
            $classPath = $path . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php';
            if (is_file($classPath)) {
                // Class File found, include it and stop the search
                require_once $classPath;

                // If Cache file is enabled, set found class path in cache file as JSON Object
                if (defined('X_AUTOLOAD_CACHE_FILE') && X_AUTOLOAD_CACHE_FILE) {
                    self::$cachedAutoloadClasses = array();
                    if (is_file(X_AUTOLOAD_CACHE_FILE)) {
                        self::$cachedAutoloadClasses = json_decode(file_get_contents(X_AUTOLOAD_CACHE_FILE), true);
                    }
                    self::$cachedAutoloadClasses[$className] = $classPath;
                    file_put_contents(X_AUTOLOAD_CACHE_FILE, json_encode(self::$cachedAutoloadClasses));
                }
                return;
            }
        }
    }

}

// Set Autoload Function
spl_autoload_register('X_Autoload::__autoload', true, true);
